<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import { useRoute } from "vue-router";
import { useK8SApi } from "@/views/domain/kubeHud/api/k8s/k8s";
import { Service, Pod } from "@/views/domain/kubeHud/api/k8s/types";
import ResourceDetailsContainer from "../components/ResourceDetailsContainer.vue";
import KDescGroup from "../components/KDescGroup.vue";
import KDescRow from "../components/KDescRow.vue";
import InTagLine from "../components/InTagLine.vue";
import MetadataDescription from "../components/MetadataDescription.vue";
import KPodList from "../pod/widgets/KPodList.vue";
import PodContainerStatusCardFlow from "../pod/widgets/PodContainerStatusCardFlow.vue";
import PortList from "../components/PortList.vue";

const { serviceRepo } = useK8SApi();

type Prop = {
  name?: string;
  namespace?: string;
};

const route = useRoute();

const props = defineProps<Prop>();

const model = ref<Service>();
const dsPods = ref<Pod[]>();

const loading = ref(false);
const query = reactive<{
  name?: string;
  namespace?: string;
}>({});

const reload = async () => {
  loading.value = true;

  const { ok, data } = await serviceRepo.getServiceDetail({
    namespace: query.namespace,
    name: query.name
  });

  if (ok) {
    model.value = data;
  }

  loading.value = false;
};

onMounted(() => {
  query.name = (route.query?.name as any) ?? props.name;
  query.namespace = (route.query?.namespace as any) ?? props.namespace;
  reload();
});
</script>

<template>
  <ResourceDetailsContainer
    v-if="model"
    :title="'Service: ' + model?.metadata?.name"
  >
    <MetadataDescription :metadata="model.metadata">
      <KDescRow label="Type" :content="model.spec?.type" />
      <KDescRow label="Cluster IP" :content="model.spec?.clusterIP" />
      <KDescRow v-if="model?.spec?.selector" label="Selector">
        <el-space wrap direction="vertical" alignment="start">
          <InTagLine
            v-for="(item, label) in model?.spec?.selector"
            :key="label"
            :title="label"
            :content="item"
          />
        </el-space>
      </KDescRow>
    </MetadataDescription>

    <KDescGroup title="Ports">
      <PortList :ports="model.spec?.ports" />
    </KDescGroup>
  </ResourceDetailsContainer>
  <div v-else v-loading="true" />
</template>
<style lang="scss" scoped></style>
